package net.kleinhenz.droidshop;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import net.kleinhenz.droidshop.R;
import net.kleinhenz.droidshop.model.ListEntry;
import net.kleinhenz.droidshop.model.Product;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class ProductListActivity extends ListActivity implements ListAdapter
{
	public static int MENUITEM_DELETEALL = 0;
	public static int MENUITEM_ABOUT = 1;
	public static int MENUITEM_SHARE = 2;

	private static final int CONTEXT_DELETE = 0;
	private static final int CONTEXT_OPEN = 1;
	private static final int CONTEXT_SHARE = 2;
	
	private static ListFactory listFactory = null;

	private List<DataSetObserver> observers = new ArrayList<DataSetObserver>();
	private List<Product> productList = null;
	private List<ListEntry> entries = null; 
	private ProductInfoThread productInfoThread = null;
	private ProgressDialog progressDialog = null;

	private String list = null;
	
	private Handler handler = new Handler() {
	    @Override
        public void handleMessage(android.os.Message msg) 
	    {
	    	if (msg.what==ProductInfoThread.ERROR_PARSING)
				showError(getResources().getString(R.string.error_parsing));
	    	else if (msg.what==ProductInfoThread.ERROR_RETRIEVING)
				showError(getResources().getString(R.string.error_loading));
	    	else
	    	{
		    	progressDialog.dismiss();
				productList = productInfoThread.getResult();
				Log.d("DroidShop", "Got productList. Entries: " + (productList==null?0:productList.size()));				
				
				if (productList==null || productList.isEmpty())
				{
					Log.d("DroidShop", "No result.");				
					showError(getResources().getString(R.string.no_match));
				}
				else
				{					
					Intent droidShopTabsIntent = new Intent(ProductListActivity.this, DroidShopTabsActivity.class);
					droidShopTabsIntent.putExtra("product", productList.get(0));
					startActivity(droidShopTabsIntent);
				}
	    	}
	    	productInfoThread = null;
        }
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);

		list = getIntent().getExtras().getString("list");
		this.entries = getListFactory().retrieveList(list);

		if (this.entries.isEmpty())
			new AlertDialog.Builder(this)
				.setTitle(getResources().getString(R.string.warning))
				.setMessage(getResources().getString(R.string.list_empty))
				.setPositiveButton(R.string.back, new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						finish();						
					}
				})
				.show();
		
		getListView().setPadding(5, 5, 5, 5);
		getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		registerForContextMenu(getListView());
		setListAdapter(this);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) 
	{
		super.onCreateOptionsMenu(menu);
		menu.clear();
		menu.add(0, CONTEXT_DELETE, 0, getResources().getString(R.string.context_deletelistentry));
		menu.add(0, CONTEXT_OPEN, 1, getResources().getString(R.string.context_openlistentry));
		menu.add(0, CONTEXT_SHARE, 1, getResources().getString(R.string.context_share));
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) 
	{
		AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
		ListEntry entry = entries.get(info.position);
		if (item.getItemId()==CONTEXT_DELETE)
		{
			getListFactory().removeFromList(entry);
			entries.remove(entry);
			notifyObservers();
			return true;
		}
		else if (item.getItemId()==CONTEXT_OPEN)
		{
			openItem(entry);
			return true;
		}
		else if (item.getItemId()==CONTEXT_SHARE)
		{
			//String link = getResources().getString(R.string.share_link) + product.getEan();
			URL url = null;
			try
			{
				url = new URL(entry.getDetailUrl());
			}
			catch (MalformedURLException e)
			{
				Log.e(DroidShop.APP_NAME, "Error getting URL instance from string url: " + e.getMessage() + " url=" + entry.getDetailUrl());
				return true;
			}
			String link = DroidShopTabsActivity.shortenLink(url);
			String text = getResources().getString(R.string.share_text).replace("%LINK%", link);
			
			Intent sendIntent = new Intent(Intent.ACTION_SEND);
			sendIntent.putExtra(Intent.EXTRA_TEXT, text); 
			sendIntent.putExtra(Intent.EXTRA_SUBJECT, getResources().getString(R.string.share_subject)); 
			sendIntent.setType("text/plain");

           	this.startActivity(Intent.createChooser(sendIntent, getResources().getString(R.string.share_with)));
			return true;
		}
		else 
			return super.onContextItemSelected(item);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    super.onCreateOptionsMenu(menu);
		menu.clear();
	    menu.add(0, MENUITEM_DELETEALL, 0, R.string.menu_deleteall)
	        .setIcon(android.R.drawable.ic_menu_delete);
	    menu.add(0, MENUITEM_ABOUT, 1, R.string.menu_about)
	    	.setIcon(android.R.drawable.ic_menu_info_details);
	    menu.add(0, MENUITEM_SHARE, 4, R.string.menu_share)
        	.setIcon(android.R.drawable.ic_menu_share);
	    return true;
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) 
	{
		if (item.getItemId()==MENUITEM_ABOUT)
		{
			new AlertDialog.Builder(this)
            .setTitle(getResources().getString(R.string.about_title))
            .setMessage(getResources().getString(R.string.about).replace("%VERSION%", DroidShop.getMotd().getVersionMajor() + "." + DroidShop.getMotd().getVersionMinor() + "." + DroidShop.getMotd().getVersionMicro()))
            .setPositiveButton(android.R.string.ok, null)
            .show();
		}
		else if (item.getItemId()==MENUITEM_DELETEALL)
		{
			new AlertDialog.Builder(this)
		      .setMessage(R.string.are_you_sure)
		      .setPositiveButton(R.string.yes, new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) 
				{
					getListFactory().removeAllFromList(list);
					entries.clear();
					notifyObservers();
					Toast.makeText(ProductListActivity.this, getResources().getString(R.string.all_deleted), Toast.LENGTH_SHORT).show(); 
				}		    	  
		      })
		      .setNegativeButton(R.string.no, null)
		      .show();
		}	
		else if (item.getItemId()==MENUITEM_SHARE)
		{
			//String link = getResources().getString(R.string.share_link) + product.getEan();
			StringBuffer text = new StringBuffer(getResources().getString(R.string.share_list_text));

			for (ListEntry thisEntry : entries)
			{
				text.append('\n');
				text.append(thisEntry.getTitle());
				text.append('\n');
				text.append(thisEntry.getAuthor());
				text.append('\n');
				text.append(thisEntry.getDetailUrl());
				text.append('\n');
			}
			text.append("--\n");
			text.append("DroidShop - Smart Android Mobile Shopping\n");
			text.append("www.droidshop.org\n");
			
			Intent sendIntent = new Intent(Intent.ACTION_SEND);
			sendIntent.putExtra(Intent.EXTRA_TEXT, text.toString()); 
			sendIntent.putExtra(Intent.EXTRA_SUBJECT, getResources().getString(R.string.share_list_subject)); 
			sendIntent.setType("text/plain");

           	this.startActivity(Intent.createChooser(sendIntent, getResources().getString(R.string.share_with)));
		}	
		return true;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) 
	{
		openItem(entries.get(position));
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) 
	{
		LinearLayout layout = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.listentry, null, false);

		ListEntry thisListEntry = entries.get(position);
		((TextView)layout.findViewById(R.id.ListEntryName)).setText(thisListEntry.getTitle());
		((TextView)layout.findViewById(R.id.ListEntryAuthor)).setText(thisListEntry.getAuthor());
		((TextView)layout.findViewById(R.id.ListEntryTypeDate)).setText(thisListEntry.getType() + ", " + thisListEntry.getDate().toLocaleString());
		ImageView productImage = ((ImageView)layout.findViewById(R.id.ListEntryImage));
		// this could cause stuttering. do it in a thread
		productImage.setImageDrawable(ImageCache.fetch(this, thisListEntry.getImageUrl(), ImageCache.THUMBNAIL));
		productImage.setAdjustViewBounds(true);
		productImage.setMaxWidth(70);
		
		return layout;
	}
	
	@Override
	public int getItemViewType(int position) 
	{
		return 0;
	}

	@Override
	public int getViewTypeCount() 
	{
		return 1;
	}

	@Override
	public Object getItem(int position) 
	{
		return entries.get(position);
	}

	@Override
	public boolean areAllItemsEnabled() 
	{
		return true;
	}

	@Override
	public boolean isEnabled(int position) 
	{
		return true;
	}

	@Override
	public int getCount() 
	{
		return entries.size();
	}

	@Override
	public long getItemId(int position) 
	{
		return (entries.get(position)).getId();
	}

	@Override
	public boolean hasStableIds() 
	{
		return true;
	}

	@Override
	public boolean isEmpty() 
	{
		return entries.isEmpty();
	}

	@Override
	public void registerDataSetObserver(DataSetObserver observer) 
	{
		observers.add(observer);
	}

	@Override
	public void unregisterDataSetObserver(DataSetObserver observer) 
	{
		observers.remove(observer);
	}

	private ListFactory getListFactory()
	{
		if (listFactory==null)
			listFactory = new ListFactory(this);
		return listFactory;
	}

	private void openItem(ListEntry item) 
	{		
		progressDialog = ProgressDialog.show(this, getResources().getString(R.string.working), getResources().getString(R.string.getting_info), true, false);
		
        productInfoThread = new ProductInfoThread(this, ProductInfoThread.Mode.LOOKUP, item.getKeywords(), getResources().getString(R.string.locale), handler);
        productInfoThread.start();		
	}
	
	private void showError(String message)
	{
		new AlertDialog.Builder(this)
        .setTitle(getResources().getString(R.string.error))
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setMessage(message)
        .setPositiveButton(getResources().getString(R.string.return_list), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) 
                {
                	// NOP
                }
        }).show();
	}

	private void notifyObservers() 
	{
		for (DataSetObserver observer : observers)
		{
			observer.onChanged();
		}
	}
}
